import { render, createVNode } from "vue";
import CoolMsgCom from "./index.vue";
// 消息实例数组
const instances = [];
const removeContainer = (ele) => {
  const index = instances.findIndex((item) => item === ele);
  if (~index) {
    instances.splice(index, 1);
  }
};
const addContainer = (ele) => {
  instances.push(ele);
};

const createMount = (opts) => {
  const { duration } = opts;
  // 创建一个 div 容器
  const container = document.createElement("div");
  // 创建 CoolMsgCom 实例，createVNode 的性能比 h 更好
  const vm = createVNode(CoolMsgCom, opts);
  // 把实例 render 到容器上
  render(vm, container);
  addContainer(container);
  // 把容器渲染到 body 上
  document.body.appendChild(container);
  const destory = () => {
    const timer = setTimeout(() => {
      render(null, container);
      removeContainer(container);
      document.body.removeChild(container);
      clearTimeout(timer);
    }, 500); // 500 为动画结束时间，根据情况修改
  };

  const timer = setTimeout(() => {
    destory();
    clearTimeout(timer);
  }, 2000);

  return { destory };
};
function CoolMsg(options) {
  if (typeof options === "string") {
    // eslint-disable-next-line
    options = {
      message: options || "",
    };
  } else {
    // eslint-disable-next-line
    options = {
      ...options,
    };
  }
  return createMount(options);
}

CoolMsg.install = function (app) {
  app.component("CoolMsg", CoolMsgCom);
};

export { CoolMsg };
